package com.rentalHome.controller;

import com.rentalHome.domain.User;
import com.rentalHome.repository.UserRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by LeeXyan on 2017/02/25.
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/list")
    public ResponseEntity userList() {
        return ResponseEntity.ok(userRepository.findAll());
    }

    @PostMapping("/add")
    public ResponseEntity userAdd(@RequestParam("username") String username,
                                  @RequestParam("password") String password,
                                  @RequestParam("email") String email,
                                  @RequestParam("tel") String tel,@RequestParam("info") String info) {
        List<User> users = userRepository.findByUsername(username);
        User us = null;
        if (users.size() == 0) {
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setEmail(email);
            user.setTel(tel);
            user.setInfo(info);
            us = userRepository.save(user);
        } else {
            User user = userRepository.findOne(getId(users));
            user.setPassword(password);
            user.setEmail(email);
            user.setTel(tel);
            user.setInfo(info);
            us = userRepository.save(user);

        }
        return ResponseEntity.ok(us);
    }


    @GetMapping("/search")
    public ResponseEntity search(@RequestParam("name") String name) {
        return ResponseEntity.ok(userRepository.findByUsername(name));
    }


    @GetMapping("/delete")
    public ResponseEntity roomDelete(@RequestParam("name") String name/*, @RequestParam("info")String info, @RequestParam("isEmpty")Boolean isEmpty*/) {
        userRepository.delete(getId(userRepository.findByUsername(name)));
        return ResponseEntity.ok("ok");
    }

    public Long getId(List<User> users) {
        return users.stream().filter(user -> !StringUtils.isEmpty(user.toString())).findFirst().get().getId();
    }


}
